#include <signal.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <string.h>
#include <arpa/inet.h>

typedef struct sockaddr SA;

#define BUFFSIZE 512
int sockfd = 0;						 //定义全局的sockfd

//信号处理
//内核  1G内存
//资源分配---》大部分的资源是需要给用户态
void do_sigio(int signo) {
    char buff[512] = {0};
    struct sockaddr_in cli_addr;
    socklen_t clilen = sizeof(cli_addr);
    int rlen = recvfrom(sockfd, buff, 512, 0,
                        (SA*)&cli_addr, &clilen);		//获取cli_addr, 为后面send做准备

    printf("Recvfrom message: %s\n", buff);
    int slen = sendto(sockfd, buff, rlen, 0, (SA*)&cli_addr, clilen);
}


int main() {
    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (-1 == sockfd) {
        perror("socket");
        return 2;
    }
    signal(SIGIO, do_sigio);//注册信号处理函数

    //确定协议地址簇
    struct sockaddr_in serv_addr;
    memset(&serv_addr,  0, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(9999);
    serv_addr.sin_addr.s_addr = INADDR_ANY;

    //设置套接口属主
    fcntl(sockfd, F_SETOWN, getpid());

    //然后设置O_ASYNC 开启信号驱动IO
    int flags = fcntl(sockfd, F_GETFL);
    if (-1 == fcntl(sockfd, F_SETFL, flags | O_NONBLOCK | O_ASYNC)) {
        return 4;
    }

    if (-1 == bind(sockfd, (SA*)&serv_addr, sizeof(serv_addr))) {
        return 3;
    }

    while (1) sleep(1);
    close(sockfd);

    return 0;
}